﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Luminal;

namespace Luminoise
{
    public class Turbulence : Module
    {
        static int instanceCount = 0;
        int instanceIndex;

        public int Octaves { get; set; }
        public float Frequency { get; set; }
        public float Lacunarity { get; set; }
        public float Gain { get; set; }

        public override string FunctionName
        {
            get { return "cl_turbulence" + instanceIndex.ToString(); }
        }

        public override string GetCode()
        {
            return
@"#ifndef " + FunctionName.ToUpper() + @"
#define " + FunctionName.ToUpper() + @"

float " + FunctionName + @"(__global int *perm, Single3 input)
{
    int octaves = " + Octaves.ToString() + @";    
    float frequency = " + Frequency.ToString() + @";
    float lacunarity = " + Lacunarity.ToString() + @";
    float gain = " + Gain.ToString() + @";

    float currentWeight = 1.0f;
    float value = 0.0f;
    for (int i = 0; i < octaves; i++)
    {
        float signal = noise(perm, input.x * frequency, input.y * frequency, input.z * frequency);
        signal = fabs(signal);
        signal *= currentWeight;

        value += signal;

        currentWeight *= gain;

        frequency *= lacunarity;
    }

    return value;
}

#endif

";
        }

        public Turbulence(int octaves, float frequency, float lacunarity, float gain)
        {
            Octaves = octaves;
            Frequency = frequency;
            Lacunarity = lacunarity;
            Gain = gain;

            instanceIndex = instanceCount;
            instanceCount++;
        }
    }
}
